<?php
include_once('lib/nusoap.php');
include_once( "JO_01_configuration.php"	);
//include_once( "JO_02_function.php"		);
$JO_MySQL = new mysqli( $JO_DB_host, $JO_DB_user, $JO_DB_password, $JO_DB_database );
ini_set('soap.wsdl_cache_enabled', '0');
$server = new soap_server();
$server->soap_defencoding = 'utf-8';
$server->decode_utf8 = false;
//Khai bao thong tin cho web service
$server->configureWSDL('ReceiveMO','urn:WService');
$wsdl="http://www.mymobile.com.vn/SMSAPIWS/SMSAgentWS.asmx?wsdl";
$client = new nusoap_client($wsdl,true);
  
$server->register(
        'ReceiveMO',//khai bao ten ham
        array(		  'moid'=>'xsd:string',
			  'moseq'=>'xsd:string',
			  'src'=>'xsd:string',
			  'dest'=>'xsd:string',
			  'cmdcode'=>'xsd:string',
			  'msgbody'=>'xsd:string',
			  'opid'=>'xsd:string',
			  'username'=>'xsd:string',
			  'password'=>'xsd:string'
			  ),//input
        array('ReceiveMOResult'=>'xsd:int')//output
);
      
/*
 * ReceiveMO
 */

//get mtseqid 
function getMTSEQID(){
	try {
		global $JO_MySQL; 
		$query="SELECT * FROM `parameter` WHERE `parametername` = 'mtseqid'";
		$recordSet = $JO_MySQL->query( $query );
		while( $record = $recordSet -> fetch_array( )){
			return $record[ "value" ];
		}			        			
	} catch (Exception $e) {
		
	}
	return 0;
}
//update new mtseqid
function updateMTSEQID(){
	global $JO_MySQL; 
	$query = "update `parameter` set `value`='".(getMTSEQID()+1)."' where `parametername` = 'mtseqid'";
	if($JO_MySQL->query($query)){
		return 1;
	}
	return 0;
}
//update point in account
function updatePoint($accountid,$npoint){
	global $JO_MySQL; 
	$requesttime = gmdate("Y-m-d H:i:s", time()+(7*3600));
	print_r($requesttime.'<br/>');
	$noldpoint=checkaccountpoint($accountid);
	print_r($noldpoint.'<br/>');
	if($noldpoint==-1){
		//insert to table point
		$query = "insert into `point`(`account`,`point`,`insert`)values('".$accountid."','".$npoint."',NOW())";
	}
	else{
		//update point of account
		$query = "update `point` set `point`.`point`='".($npoint+$noldpoint)."' , `update`=NOW() WHERE `account` = '".$accountid."'";
	}
	//print_r($query.'<br/>');
	if($JO_MySQL->query($query)){
		
		return 1;
	}
	return 0;
}
//check and get point of account
function checkaccountpoint($accountid){
		global $JO_MySQL; 
		$query="SELECT `point` . * FROM `point` WHERE `account` = '".$accountid."'";
		$recordSet = $JO_MySQL->query( $query );
		$nnum=-1;
		while( $record = $recordSet -> fetch_array( )){
			$nnum=$record[ "point" ];
			break;
		}
	return $nnum;
}
//check account exist
function checkaccount($identifier){
		global $JO_MySQL; 
		$query="SELECT `key` FROM `account` WHERE `identifier` = '".$identifier."'";
		$recordSet = $JO_MySQL->query( $query );
		while( $record = $recordSet -> fetch_array( )){
			return $record[ "key" ];
				
		}
	return -1;
}
function getrbtcode($moid, $moseq, $src, $dest, $cmdcode, $msgbody, $opid,$username){
	$mttotalseg=1;
	$msgresult="JukeOn\n";
	//$msgresult.="De tim kiem nhac theo Ca Khuc,Soan tin HQ S <Ten Ca Khuc> gui 8388\n";
	//$msgresult.="De tim kiem nhac theo Ca Si,Soan tin HQ A <Ten Ca Si> gui 8388";
	//$msgresult.="De tim kiem nhac theo The Loai,Soan tin HQ G <Ten The Loai> gui 8388";
	$telconame="";
	switch($opid){
		case "VTL8x88"://viettel
			$telconame="Viettel";
			$msgresult.="Dang ky su dung dich vu nhac cho Viettel soan tin DK gui 1221\nDe cai nhac cho soan tin:BH <Ma Ca Khuc> gui 1221\n";
			break;
		case "VMS8x88"://mobile
			$telconame="MobiFone";
			$msgresult.="Dang ky su dung dich vu nhac cho Mobiphone soan tin: DK gui 9224\nDe cai nhac cho soan tin:CHON <Ma Ca Khuc> Gui 9224\n";
			break;
		case "GPC8x88"://vinaphone
			$telconame="VinaPhone";
			$msgresult.="De cai nhac cho,Buoc 1 soan tin:TUNE <Ma Ca Khuc> gui 9194\nBuoc 2 soan tin:MD <Ma Ca Khuc> gui 9194\n";
			break;
		case "VNM8x88"://vietnamobile
			$telconame="VietnamMobile";
			$msgresult.="Dang ky su dung dich vu nhac cho Vietnamobile soan tin: DK HR  send 123\nBuoc 2 soan tin:MUA <Ma Ca Khuc> gui 2345 de cai nhac cho\n";
			break;
		//thieu beeline
		default:
		$msgresult.="He Thong Dang Nang Cap";
	}
	$msgresult2="";
	$procresult=0;
	//musicname
	if(strlen($msgbody)>=6){
		$keysearch=trim(substr (  $msgbody, 4 ), " \t\n\r\0\x0B");
		$keysearch_noreplace=trim(substr (  $msgbody, 4 ), " \t\n\r\0\x0B");
		//replace charac
		$vowels = array( "(", ")", "'","*","&","-"," ","_","!"," ","<",">");
		$keysearch = str_replace("đ","d", $keysearch);
		$keysearch = str_replace($vowels,"", $keysearch);
		$key=trim(substr (  $msgbody, 3,2 ), " \t\n\r\0\x0B");
		if($key=="S" || $key=="s"){
					$musicname=$keysearch;
					$array_rbtcode=getrbtcode_music($musicname,$opid);
					if(count($array_rbtcode)==0){
						$msgresult="Mang ".$telconame." chua ho tro nhac cho cho Bai Hat:[".$keysearch_noreplace."]\nSoan Tin HQ A <TenCaSi> gui 8388 de tim nhac cho theo Ca Si.";
						$msgresult2="Soan Tin HQ S <TenBaiHat> gui 8388 de tim nhac cho theo TenBaiHat.\nSoan Tin HQ G <TenTheLoai> gui 8388 de tim nhac cho theo Theloai.";
						$procresult=1;
					}else{
						$msgresult.="Cac bai hat ten :[".$keysearch_noreplace."]\n";
						foreach ($array_rbtcode as $value) {
							$content=$value["note"].":";
							$content.=$value["rbtcode"]."\n";
							if(strlen($msgresult)+strlen($content)<160){
								$msgresult.=$content;
							}elseif(strlen($msgresult2)+strlen($content)<160){
								$msgresult2.=$content;
							}else{
								break;
							}
							
							
						}
						$procresult=1;
					}
		}elseif($key=="A" || $key=="a"){//artist name
				$artist=$keysearch;
				$array_rbtcode=getrbtcode_artist($artist,$opid);
				if(count($array_rbtcode)==0){
					$msgresult="Mang ".$telconame." chua ho tro nhac cho cho Ca Si:[".$keysearch_noreplace."]\nSoan Tin HQ A <TenCaSi> gui 8388 de tim nhac cho theo Ca Si.";
					$msgresult2="Soan Tin HQ S <TenBaiHat> gui 8388 de tim nhac cho theo TenBaiHat.\nSoan Tin HQ G <TenTheLoai> gui 8388 de tim nhac cho theo Theloai.";
					$procresult=1;
				}else{
					$msgresult.="Cac bai nhac cua ca si :[".$keysearch_noreplace."]\n";
					foreach ($array_rbtcode as $value) {
							
							$content=$value["note"].":";
							$content.=$value["rbtcode"]."\n";
							if(strlen($msgresult)+strlen($content)<160){
								$msgresult.=$content;
							}elseif(strlen($msgresult2)+strlen($content)<160){
								$msgresult2.=$content;
							}else{
								break;
							}
					}
					$procresult=1;
				}
		}elseif($key=="G" || $key=="g"){//gender gender
			$gender=$keysearch;
				$array_rbtcode=getrbtcode_gender($gender,$opid);
				if(count($array_rbtcode)==0){
					$msgresult="Mang ".$telconame." chua ho tro nhac cho cho The Loai:[".$keysearch_noreplace."]\nSoan Tin HQ A <TenCaSi> gui 8388 de tim nhac cho theo Ca Si.";
					$msgresult2="Soan Tin HQ S <TenBaiHat> gui 8388 de tim nhac cho theo TenBaiHat.\nSoan Tin HQ G <TenTheLoai> gui 8388 de tim nhac cho theo Theloai.";
					$procresult=1;
				}else{
					$msgresult.="Cac bai nhac thuoc the loai: [".$keysearch_noreplace."]\n";
					foreach ($array_rbtcode as $value) {
							
							$content=$value["note"].":";
							$content.=$value["rbtcode"]."\n";
							if(strlen($msgresult)+strlen($content)<160){
								$msgresult.=$content;
							}elseif(strlen($msgresult2)+strlen($content)<160){
								$msgresult2.=$content;
							}else{
								break;
							}
					}
					$procresult=1;
				}
		}else{
			$msgresult="Cu Phap Tin Nhan Khong Dung.\nSoan Tin HQ A <TenCaSi> gui 8388 de tim nhac cho theo Ca Si.";
			$msgresult2="Soan Tin HQ S <TenBaiHat> gui 8388 de tim nhac cho theo TenBaiHat.\nSoan Tin HQ G <TenTheLoai> gui 8388 de tim nhac cho theo Theloai.";
			$mttotalseg=2;
		}
	}else{
		$msgresult="Cu Phap Tin Nhan Khong Dung.\nSoan Tin HQ A <TenCaSi> gui 8388 de tim nhac cho theo Ca Si.";
		$msgresult2="Soan Tin HQ S <TenBaiHat> gui 8388 de tim nhac cho theo TenBaiHat.\nSoan Tin HQ G <TenTheLoai> gui 8388 de tim nhac cho theo Theloai.";
		$mttotalseg=2;
	}
	if($msgresult2!=""){
		$mttotalseg=2;
		SendMT( $moid,$moseq, $src, $dest, $cmdcode, $msgresult, $mttotalseg, 1, $procresult, $opid);
		SendMT( $moid,$moseq, $src, $dest, $cmdcode, $msgresult2, $mttotalseg, 2, 0, $opid);
	}else{
		SendMT( $moid,$moseq, $src, $dest, $cmdcode, $msgresult, $mttotalseg, 1, $procresult, $opid);
	}
}
function SendMT($moid,$moseq,$src,$dest,$cmdcode,$msgresult,$mttotalseg,$mtseqref,$procresult,$opid){
    $newmtseqid=getMTSEQID();
	$wsdl="http://www.mymobile.com.vn/SMSAPIWS/SMSAgentWS.asmx?wsdl";
	$client = new nusoap_client($wsdl,true);
    if(updateMTSEQID()){
        $requesttime = gmdate("YmdHis", time()+(7*3600));
        $result = $client->call('SendMT',array(
                                            'mtseq'		=>$newmtseqid,
                                            'moid'		=>$moid,
                                            'moseq'		=>$moseq,
                                            'src'		=>$src,
                                            'dest'		=>$dest,
                                            'cmdcode'           =>$cmdcode,
                                            'msgbody'           =>$msgresult,
                                            'msgtype'           =>'Text',
                                            'msgtitle'          =>'',
                                            'mttotalseg'        =>$mttotalseg,
                                            'mtseqref'          =>$mtseqref,
                                            'cpid'		=>'222',
                                            'reqtime'           =>$requesttime,
                                            'Procresult'        =>$procresult,
                                            'opid'		=>$opid,
                                            'username'          =>'neowiz',
                                            'password'          =>'Y2mz7Dkwj'
                                            ));

    }


    //return $result;
}
function ReceiveMO($moid, $moseq, $dest, $src, $cmdcode, $msgbody, $opid,$username){
     global $JO_MySQL;
        // Connect Database
        //su dung mysql_connect cung duoc
     $requesttime = gmdate("Y-m-d H:i:s", time()+(7*3600));

    $query ="INSERT INTO `sms` (`moid`,`moseq`,`src`,`dest`,`cmdcode`,`msgbody`,`opid`,`requesttime`,`point`)
					VALUES ('".$moid."','".$moseq."','".$src."','".$dest."','".$cmdcode."','".$msgbody."','".$opid."','".$requesttime."','0')";
	if($JO_MySQL->query($query)){
				//getrbtcode($moid, $moseq, $src, $dest, $cmdcode, $msgbody, $opid,$username);
				//return 202;
        if(strtoupper($cmdcode)=="HT"){
			$mttotalseg=1;
			$mtseqref=1;
			$msgresult='Cam on ban da tham gia chuong trinh binh chon tai JukeOn.';
			$procresult=1;
			$result = SendMT( $moid,$moseq, $src, $dest, $cmdcode, $msgresult, $mttotalseg, $mtseqref, $procresult, $opid);
		}elseif(strtoupper($cmdcode)=="HQ"){
			getrbtcode($moid, $moseq, $src, $dest, $cmdcode, $msgbody, $opid,$username);
			return 202;
		}elseif(strtoupper($cmdcode)=="NP"){
		
		//$requesttime = gmdate("YmdHis", time()+(7*3600));
			try{
				$msgresult='Hello, this is jukeon';
				//get and update mtseqid
				$newmtseqid=getMTSEQID();
				$procresult=0;
				if(updateMTSEQID()){
					//get account name
					$accountname=trim(substr (  $msgbody, 2 ), " \t\n\r\0\x0B");
					//check account exist
					$accountid=checkaccount($accountname);
					if($accountid==-1){
						$msgresult='account does not exist';
						$procresult=0;
					}
					else{

						//get newpoint
						$npoint=0;
						switch($src){
						case 8188:
							$npoint=1;
							break;
						case 8288:
							$npoint=2;
							break;
						case 8388:
							$npoint=3;
							break;
						case 8588:
							$npoint=5;
							break;
						case 8788:
							$npoint=15;
							break;
						default:
							$npoint=0;
						}
						if($npoint>0){
							//update point
							if(updatePoint($accountid,$npoint)){
								//update sms???
								$queryUpdatePoint = "update `sms` set `point`='".$npoint."'  WHERE `moid` = '".$moid."' and `moseq`='".$moseq."'";
								$msgresult='Welcome to JukeOn. You have charged '.$npoint.' points to acccount '.$accountname.' successfully';
								$JO_MySQL->query($queryUpdatePoint);
								//{
									$procresult=1;
								//}else{
								//	$procresult=0;
								//}
							}else{
								$msgresult='charge fails';
								$procresult=0;
							}
						}
						else{
							//point is zero
							$msgresult='Cu Phap Tin Nhan Khong Dung.\nSoan Tin HQ A <TenCaSi> gui 8388 de tim nhac cho theo Ca Si.';
							//$msgresult='this SMS is not support with 8088';
							
							$procresult=0;
						}


					}
				}else{
					$msgresult='server busy';
					$procresult=0;
				}
			//send sms to customer
					$mttotalseg=1;
					$mtseqref=1;
			$result = SendMT( $moid,$moseq, $src, $dest, $cmdcode, $msgresult, $mttotalseg, $mtseqref, $procresult, $opid);
			}
			catch (Exception $e) {
						return 200;
			}
		}
		if($procresult==0){
			return 200;
		}
		return 202;
	}else{

		return 400;
	}
}
function getrbtcode_music($musicname,$opid){
	global $JO_MySQL;
	$query="    select rbt.rbtcode,rbt.`note`,music.`subject`,LENGTH(music.`subject`) as srt
                    from rbt,music
                    where   rbt.telco='".$opid."'
                            and rbt.music=music.`key`
                            and music.`key` in
                                (
                                select music.`key`
                                from rbt,music
                                where music.`key`=rbt.music
                                        and 
										REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(music.`subject`,'d','d'),'(',''),')',''),'\'',''),'&',''),'-',''),' ',''),'_',''),'!',''),'<',''),'>','')
										like '%".$musicname."%'
                                        and rbt.telco='".$opid."'
                                        and music.`delete` is null
                                        order by music.`subject` asc
                                )
								
                    ORDER BY srt asc

               ";
	$recordSet = $JO_MySQL->query( $query );
	$array_rbtcode = array();
	while( $record = $recordSet -> fetch_array()){
		$rbt_code=array("rbtcode"=>$record["rbtcode"],"note"=>$record["note"]);
		array_push($array_rbtcode, $rbt_code);
	}
	return $array_rbtcode;
}
function getrbtcode_artist($artist,$opid){
	global $JO_MySQL;
	$query="    select rbt.`rbtcode`,rbt.`note`,music.`subject`
                    from music,rbt
                    where music.`key`=rbt.`music`
                        and rbt.`delete` is null
                        and rbt.`telco`='".$opid."'
                        and rbt.`music` in   (    select music.`key`
                                                from music
                                                WHERE music.`delete` is NULL
                                                    and music.`artist`in
                                                    (   select artist.`key`
                                                        from artist
                                                        where
                                                            REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(artist.`name`,'đ','d'),'(',''),')',''),'\'',''),'&',''), '-',''), ' ',''),'<',''),'>','')
															like '%".$artist."%'
                                                            and artist.`delete` is null
                                                            order by LENGTH(artist.`name`) asc,artist.`name` asc
                                                    )
                                                ORDER BY music.`position` desc,LENGTH(music.`subject`) asc
                                            )
                    GROUP BY rbt.music
                    ORDER BY music.`position` desc,`provider` desc
                    limit 0,10";
	$recordSet = $JO_MySQL->query( $query );
	$array_rbtcode = array();
	while( $record = $recordSet -> fetch_array( )){
		$rbt_code=array("rbtcode"=>$record["rbtcode"],"note"=>$record["note"]);
		array_push($array_rbtcode, $rbt_code);
	}
	return $array_rbtcode;
}
function getrbtcode_gender($gender,$opid){
	global $JO_MySQL;
	$query="    select rbt.rbtcode,rbt.note,music.`subject`
                    from music,rbt
                    where music.`key`=rbt.`music`
                        and rbt.`delete` is null
                        and rbt.telco='".$opid."'
                        and rbt.music in   (    select music.`key`
                                                from music
                                                WHERE music.`delete` is NULL
                                                    and music.`genre`in
                                                    (   select genre.`key`
                                                        from genre
                                                        where
                                                            REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(genre.`subject`,'đ','d'),'(',''),')',''),'\'',''),'&',''),'<',''),'>','') 
															like '%".$gender."%'
                                                            and genre.`delete` is null
                                                            order by LENGTH(genre.`subject`) asc,genre.`subject` asc
                                                    )
                                                ORDER BY LENGTH(music.`subject`) asc
                                            )
                    GROUP BY rbt.music
                    ORDER BY music.`position` desc,`provider` desc
                    limit 0,10

               ";
	$recordSet = $JO_MySQL->query( $query );
	$array_rbtcode = array();
	while( $record = $recordSet -> fetch_array()){
		$rbt_code=array("rbtcode"=>$record["rbtcode"],"note"=>$record["note"]);
		array_push($array_rbtcode, $rbt_code);
	}
	return $array_rbtcode;
}

//Hien thi thong tin
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             